package com.nowcoder.community.community.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class sensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(sensitiveFilter.class);

    //替换的符号
    private static final String REPLACEMENT = "***";

    // 根节点
    private TrieNode rootNode = new TrieNode();

    @PostConstruct//调用构造器时自动调用
    public void init(){
        try(
                InputStream stream = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                ) {
            String keyword;
            while ((keyword = reader.readLine()) != null){
                //添加到前缀树
                this.addKeyword(keyword);
            }
        } catch (IOException e) {
            logger.error("加载铭感词文件失败！"+e.getMessage());
        }
    }

    //将一个词添加到前缀树中
    private void addKeyword(String keyword) {
        TrieNode tmpNode = rootNode;
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TrieNode subNode = tmpNode.getSubNode(c);
            if(subNode == null){
                subNode = new TrieNode();
                tmpNode.addSubNode(c,subNode);
            }

            //更新tmp节点
            tmpNode = subNode;

            //结束标志
            if(i == keyword.length()-1){
                tmpNode.setKeywordEnd(true);
            }
        }
    }

    /**
     * 过滤敏感词
     * @param text  传入的字符串
     * @return  过滤后的字符串
     */
    public String filter(String text){
        if(StringUtils.isBlank(text)){
            return null;
        }
        //前缀树指针
        TrieNode tmpNode = rootNode;
        //字符串指针1，检测开始字符
        int begin = 0;
        //字符指针2,指针1检测到存在的字符时与前缀树指针同时移动
        int position = 0;
        //结果
        StringBuilder ans = new StringBuilder();

//        while ( begin < text.length() && position < text.length() ){
//            char c = text.charAt(position);
//
//            if(isSymbol(c)){
//                if(tmpNode == rootNode){
//                    ans.append(c);
//                    begin++;
//                }
//                position++;
//                continue;
//            }
//
//            tmpNode = tmpNode.getSubNode(c);
//            if(tmpNode == null){
//                ans.append(text.charAt(begin));
//                position = ++begin;
//                tmpNode = rootNode;
//            }else if(tmpNode.isKeywordEnd()){
//                ans.append(REPLACEMENT);
//                begin = ++position;
//                tmpNode = rootNode;
//            }else {
//                position++;
//            }
//        }
//        ans.append(text.substring(begin));

        while ( begin < text.length() && position < text.length()){

            char c = text.charAt(begin);

            if(isSymbol(c)){//如果是符号，直接加入

                ans.append(c);

            }else if(tmpNode.getSubNode(c) != null){//前缀树中从根节点的子节点中存在当前字符

                position = begin;

                while (position < text.length()){

                    char ci = text.charAt(position);

                    if(!isSymbol(ci)){//如果不是符号判断是否符合前缀树

                        tmpNode = tmpNode.getSubNode(ci);

                        if(tmpNode == null){//如果为空表示不匹配，添加begin位置字符并把begin后移一位
                            ans.append(text.charAt(begin));
                            tmpNode = rootNode;
                            break;

                        }else if(tmpNode.isKeywordEnd()){//如果当前为end，匹配成功，替换为REPLACEMENT，begin更新为匹配字符串的最后一个位置
                            ans.append(REPLACEMENT);
                            tmpNode = rootNode;
                            begin = position;
                            break;
                        }
                    }
                    position++;
                }
            }else {//不存在直接加入
                ans.append(c);
            }
            begin++;
        }

        return ans.toString();
    }

    public boolean isAcceptable(String text){
        if(StringUtils.isBlank(text)){
            return true;
        }
        //前缀树指针
        TrieNode tmpNode = rootNode;
        //字符串指针1，检测开始字符
        int begin = 0;
        //字符指针2,指针1检测到存在的字符时与前缀树指针同时移动
        int position = 0;
        //结果

        while ( begin < text.length() && position < text.length() ){
            char c = text.charAt(position);

            if(isSymbol(c)){
                if(tmpNode == rootNode){
                    begin++;
                }
                position++;
                continue;
            }

            tmpNode = tmpNode.getSubNode(c);
            if(tmpNode == null){
                position = ++begin;
                tmpNode = rootNode;
            }else if(tmpNode.isKeywordEnd()){
                return false;
            }else {
                position++;
            }
        }
        return true;
    }

    //判断是否为符号
    private boolean isSymbol(Character c){
        //0x2E80~0x9FFF是东亚文字范围
        return CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    //前缀树
    private class TrieNode{
        //描述关键词结束的标识（完整的关键词的结尾标志）
        private boolean isKeywordEnd = false;

        //子节点(key->节点的字符，value->节点)
        private Map<Character,TrieNode> subNodes = new HashMap<>();

        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        //添加子节点
        public void addSubNode(Character c, TrieNode node){
            subNodes.put(c, node);
        }

        //获取子节点
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }
    }
}
